package com.xuebusi.consumer.service.impl;

import com.xuebusi.consumer.entity.Product;
import com.xuebusi.consumer.service.OrderService;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private RestTemplate restTemplate;

    @Resource
    private EurekaDiscoveryClient discoveryClient;

    /**
     * 查询商品信息2
     *
     * @param productId 商品id
     * @return
     */
    @Override
    public Product findProductById1(Long productId) {
        // 写死服务主机名和端口的方式
        String url = "http://localhost:9001/product/1";
        ResponseEntity<Product> responseEntity = restTemplate.getForEntity(url, Product.class);
        return responseEntity.getBody();
    }

    /**
     * 查询商品信息2
     *
     * @param productId 商品id
     * @return
     */
    @Override
    public Product findProductById2(Long productId) {
        // 当服务注册到Eureka注册中心之后，可以通过SpringCloud提供的
        // EurekaDiscoveryClient根据服务名称获取服务元数据(包含服务的主机地址和端口号)
        List<ServiceInstance> instances = discoveryClient.getInstances("provider-service");
        ServiceInstance instance = instances.get(0);
        // 从拉取到的元数据中获取服务的主机名和端口，拼接微服务请求URL
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/1";
        ResponseEntity<Product> responseEntity = restTemplate.getForEntity(url, Product.class);
        return responseEntity.getBody();
    }
}
